package id.net.iconpln.bb.client.view.secman;

import id.net.iconpln.bb.client.service.SecmanService;
import id.net.iconpln.bb.client.service.SecmanServiceAsync;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbUserGroup extends LayoutContainer{
	private final SecmanServiceAsync secmanService = GWT.create(SecmanService.class);
	
	private static final String generateBySystem = "Generated By System.";
	
	ListStore storeGpMaster, storeCbGroup, storeCbSubGroup;
	ListStore storeCbUser;
	
	private Grid gpMaster;
	private ComboBox cbGroup, cbSubGroup, cbUser;

    private Button bSubmit = new Button("Submit");
    private Button bDelete = new Button("Delete");

	Map mapParam;

	@Override
	protected void onRender(Element parent, int index) 
	{
	    super.onRender(parent, index);  
	    setLayout(new FitLayout());	    
	    initStore();

	    ContentPanel cp = new ContentPanel();  

	    cp.setHeading("User Group");  
	    cp.setFrame(true);  
	    cp.setSize(900, 400);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL));  
	    
	    gpMaster = createGridMasterUser();
	    gpMaster.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
	    gpMaster.getSelectionModel().addListener(Events.SelectionChange, new Listener<SelectionChangedEvent<ModelData>>() {
			@Override
			public void handleEvent(SelectionChangedEvent<ModelData> be) {
				ModelData md = (ModelData) be.getSelectedItem();
				
				ModelData dummyGroup = new BaseModelData();
				dummyGroup.set("id_group", md.get("id_group"));
				dummyGroup.set("nama_group", md.get("nama_group"));
				cbGroup.setValue(dummyGroup);

				ModelData dummyUser = new BaseModelData();
				dummyUser.set("id_user", md.get("id_user"));
				dummyUser.set("nama_user", md.get("nama_user"));
				cbUser.setValue(dummyUser);

				ModelData dummySubGroup = new BaseModelData();
				dummySubGroup.set("id_modul", md.get("id_subgroup"));
				dummySubGroup.set("keterangan", md.get("nama_subgroup"));
				cbSubGroup.setValue(dummySubGroup);
				
				bSubmit.enable();
				bDelete.enable();
			}
		});
	    
			
	    FormPanel panel = createFormInput();

	    cp.add(panel, new RowData(.4, 1));
	    cp.add(gpMaster, new RowData(.6, 1));
		
	    add(cp, new FitData(5));
	}
	
	// Store
	private void initStore()
	{
		storeGpMaster = new ListStore();
		initGridStore();
		
		storeCbGroup = new ListStore();
		secmanService.getMasterGroupAll(new AsyncCallback<List<Map>>() {
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage(), null);
			}

			public void onSuccess(List<Map> result) {	
				storeCbGroup.removeAll();
				storeCbGroup.add(ClientModule.setListBaseModelFromListMap(result));
			}
		});
		
		storeCbSubGroup = new ListStore();
//		secmanService.getMasterModulAll(new AsyncCallback<List<Map>>() {
//			public void onFailure(Throwable caught) {
//				GWT.log(caught.getMessage(), null);
//			}
//
//			public void onSuccess(List<Map> result) {	
//				storeCbSubGroup.removeAll();
//				storeCbSubGroup.add(ClientModule.setListBaseModelFromListMap(result));
//			}
//		});


		Map map = new FastMap();
		//map.put("id_unit", "IP.SUR");
		map.put("id_unit", Registry.get("idPltu"));
		
		storeCbUser = new ListStore();
		secmanService.getMasterUser(map, new AsyncCallback<List<Map>>() {
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage(), null);
			}

			public void onSuccess(List<Map> result) {	
				storeCbUser.removeAll();
				storeCbUser.add(ClientModule.setListBaseModelFromListMap(result));
			}
		});
	}
	
	private void initGridStore()
	{
		Map map = new FastMap();
		//map.put("id_unit", "IP.SUR");
		map.put("id_unit", Registry.get("idPltu"));
		secmanService.getMasterUserAccess(map, new AsyncCallback<List<Map>>() {
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage(), null);
			}

			public void onSuccess(List<Map> result) {
				storeGpMaster.removeAll();
				storeGpMaster.add(ClientModule.setListBaseModelFromListMap(result));
			}
		});
	}
	
	// Grid
	private Grid createGridMasterUser()
	{
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
		
		ColumnConfig column;

		column = new ColumnConfig("id_user","ID User", 50);
		configs.add(column);
		
		column = new ColumnConfig("nama_user","Nama Login", 150);
		configs.add(column);

		column = new ColumnConfig("id_group","ID Group", 50);
		configs.add(column);
		
		column = new ColumnConfig("nama_group","Nama Group", 150);
		configs.add(column);

		column = new ColumnConfig("id_subgroup","ID Subgroup", 50);
		configs.add(column);
		
		column = new ColumnConfig("nama_subgroup","Nama Subgroup", 150);
		configs.add(column);
		
		storeGpMaster.setMonitorChanges(true);
		ColumnModel cm = new ColumnModel(configs);
		gpMaster = new Grid(storeGpMaster, cm);
		gpMaster.getView().setEmptyText("Data tidak ditemukan");
		gpMaster.setBorders(true);
		gpMaster.setStripeRows(true);
		
		return gpMaster;
	}
	
	// Form Panel
	private FormPanel createFormInput()
	{
		FormPanel panel = new FormPanel();
		panel.setHeaderVisible(false);
		
		FormLayout flLogin = new FormLayout();
		flLogin.setLabelWidth(100);
		
		FieldSet fsLogin = new FieldSet();
		fsLogin.setHeading("Property User dan Group");
		fsLogin.setCollapsible(false);
		fsLogin.setLayout(flLogin);
		
		cbUser = new ComboBox();
		cbUser.setId("cbUser");
		cbUser.setFieldLabel("User");
		cbUser.setDisplayField("nama_user");
		cbUser.setValueField("id_user");
		cbUser.setTriggerAction(TriggerAction.ALL);
		cbUser.setStore(storeCbUser);
		cbUser.setEmptyText("Select User..."); 
		cbUser.setTypeAhead(false);
		cbUser.setEditable(false);
		fsLogin.add(cbUser);
	    
		cbGroup = new ComboBox();
		cbGroup.setId("cbGroup");
		cbGroup.setFieldLabel("Group");
		cbGroup.setDisplayField("nama_group");
		cbGroup.setValueField("id_group");
		cbGroup.setTriggerAction(TriggerAction.ALL);
	    cbGroup.setStore(storeCbGroup);
	    cbGroup.setEmptyText("Select Group...");  
	    cbGroup.setTypeAhead(false);
	    cbGroup.setEditable(false);
	    
	    cbGroup.addListener(Events.SelectionChange, new Listener<SelectionChangedEvent<ModelData>>() {
			@Override
			public void handleEvent(SelectionChangedEvent<ModelData> be) {
				cbSubGroup.clear();
				
				ModelData md = (ModelData) be.getSelectedItem();
				
				Map map = new FastMap();
				map.put("id_group", md.get("id_group"));

				secmanService.getMasterModul(map, new AsyncCallback<List<Map>>() {
					public void onFailure(Throwable caught) {
						GWT.log(caught.getMessage(), null);
					}
		
					public void onSuccess(List<Map> result) {	
						storeCbSubGroup.removeAll();
						storeCbSubGroup.add(ClientModule.setListBaseModelFromListMap(result));
					}
				});
			}
		});
	    
	    fsLogin.add(cbGroup);
	    
	    cbSubGroup = new ComboBox();
	    cbSubGroup.setId("cbSubGroup");
	    cbSubGroup.setFieldLabel("Sub Group");
	    cbSubGroup.setDisplayField("keterangan");
	    cbSubGroup.setValueField("id_modul");
	    cbSubGroup.setTriggerAction(TriggerAction.ALL);
	    cbSubGroup.setStore(storeCbSubGroup);
	    cbSubGroup.setEmptyText("Select Sub Group...");  
	    cbSubGroup.setTypeAhead(false);
	    cbSubGroup.setEditable(false);
	    fsLogin.add(cbSubGroup);

		panel.add(fsLogin);

	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);	    
	    p.setButtonAlign(HorizontalAlignment.RIGHT);

	    bSubmit.addListener(Events.OnClick, new SelectionListener<ButtonEvent>() {
			public void handleEvent(ButtonEvent be)
			{
				try
				{	
					//insert baru
		    	  	mapParam = new FastMap();	
		    		mapParam.put("id_group", cbGroup.getValue().get("id_group"));	
		    		mapParam.put("id_user", cbUser.getValue().get("id_user"));	
		    		mapParam.put("id_modul", cbSubGroup.getValue().get("id_modul"));
		    		
					secmanService.manageUserGroup("INSERT", mapParam, new AsyncCallback<List<Map>>() {
						public void onFailure(Throwable caught) {
							GWT.log(caught.getMessage(), null);
						}

						public void onSuccess(List<Map> result) {
							String gethasil = result.get(0).get("gethasil").toString();
							
							if (gethasil.equalsIgnoreCase("TRUE"))
							{
								initGridStore();
								MessageBox.info("Tambah", "Berhasil Menyimpan", null);
							}
							else
							{
								MessageBox.alert("Tambah", "Gagal Menyimpan: " + gethasil, null);
							}
						}
					});
				}
				catch(Exception ex)
				{
					MessageBox.alert("Kesalahan", ex.getMessage().toString(), null);
				}
			}

			@Override
			public void componentSelected(ButtonEvent ce) {}
		});
	    
	    bDelete.disable();
	    bDelete.addListener(Events.OnClick, new SelectionListener<ButtonEvent>() {
			public void handleEvent(ButtonEvent be)
			{
				MessageBox box = new MessageBox();  
		        box.setButtons(MessageBox.YESNO);  
		        box.setIcon(MessageBox.QUESTION);  
		        box.setTitle("Delete");  
		        box.addCallback(l);  
		        box.setMessage("Delete user group: <br>" + cbUser.getValue().get("nama_user") + " <-> " + cbGroup.getValue().get("nama_group") + "?");  
		        box.show();  
			}

			@Override
			public void componentSelected(ButtonEvent ce) {}
		});
	    
	    
	    Button bReset = new Button("Reset",new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {

				bDelete.disable();
				
				Info.display("Informasi", "Reset form input..");
			}
		});

	    p.addButton(bSubmit);
	    p.addButton(bDelete);
	    p.addButton(bReset);

	    panel.add(p);
		return panel;
	}
	
	// listener
    final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {  
		public void handleEvent(MessageBoxEvent ce) {  
		    if(ce.getButtonClicked().getText().equalsIgnoreCase("Yes"))
		    {

	    	  	mapParam = new FastMap();
	    		mapParam.put("id_group", cbGroup.getValue().get("id_group"));	
	    		mapParam.put("id_user", cbUser.getValue().get("id_user"));	
	    		mapParam.put("id_modul", cbGroup.getValue().get("id_modul"));	
	    		
				secmanService.manageUserGroup("DELETE", mapParam, new AsyncCallback<List<Map>>() {
					public void onFailure(Throwable caught) {
						GWT.log(caught.getMessage(), null);
					}

					public void onSuccess(List<Map> result) {
						String gethasil = result.get(0).get("gethasil").toString();
						
						if (gethasil.equalsIgnoreCase("TRUE"))
						{
							initGridStore();
							MessageBox.info("Delete", "User Group dihapus", null);
						}
						else
						{
							MessageBox.alert("Delete", "Gagal Menghapus: " + gethasil, null);
						}
					}
				});
		    } else
		    {
		    	MessageBox.alert("Delete", "Batal Hapus User Group", null);
		    }
		}  
    }; 
}
